package com.proj.hot.activity;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.proj.hot.GlobalParams;
import com.proj.hot.R;
import com.proj.hot.utils.DebugUtil;
import com.proj.hot.utils.TimeUtil;
import com.proj.hot.widget.XWDialog_yes;

import org.json.JSONObject;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.IOException;
import java.util.ArrayList;

/**
 * 播放器播放页
 *
 */
public class VODPlayActivity extends TipsBaseActivity implements MediaPlayer.OnPreparedListener, MediaPlayer.OnBufferingUpdateListener, MediaPlayer.OnCompletionListener,
        MediaPlayer.OnErrorListener, MediaPlayer.OnInfoListener {

    private final String TAG = getClass().getSimpleName();


    String mVideoUrl;
    MediaPlayer mPlayer;
    VodVideoView mVideoView;
    SurfaceHolder mSurfaceHolder;



    //播放控制相关
    RelativeLayout mVideoViewParentLayout;
    RelativeLayout mBufferingPage;
    TextView mBufferingHint;
    private ViewGroup mVgControlPanel;
    private SeekBar mSeekBar;
    private TextView mTvCurrentPosition;
    private TextView mTvDuration;
    private ImageView playbtn;


    //延迟自动隐藏
    private Handler mPanelDelayHideHandler;
    private Runnable mPanelDelayHideRunnable;
    private ArrayList<View> mNeedDelayHideViews;


    //免费观看时长
    private int freeDuratio;
    private RelativeLayout payinfolay;

    TextView pay_price_text;
    ImageView wxcode,alcode;
    String contentid;

    String wxpic;
    String alpic;
    String price;
    boolean isPay=false;
    boolean isfinish=false;
    int mLastPosition = -1;


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            if(msg.what == 0) {

                try {

                    mPlayer.stop();
                    mPlayer.reset();
//                    mLastPosition = 0;
                    startupPlay();

                } catch (Exception e) {

                }

            }
            if(msg.what == 1) {
                mVgControlPanel.setVisibility(View.INVISIBLE);
                payinfolay.setVisibility(View.VISIBLE);
                ImageLoader.getInstance().displayImage(wxpic, wxcode);
                ImageLoader.getInstance().displayImage(alpic, alcode);
                pay_price_text.setText("￥" + price);


                if (mPlayer != null) {
                    if (mPlayer.isPlaying()) {
                        mPlayer.pause();
                        playbtn.setImageResource(R.drawable.ic_play);
                    }
                }

                mHandler.sendEmptyMessageDelayed(3, 3000);

            }

            if(msg.what == 3) {

                if (isPay) {
                    Toast.makeText(VODPlayActivity.this, "支付成功！", Toast.LENGTH_LONG).show();
                    payinfolay.setVisibility(View.INVISIBLE);
                    if (mPlayer != null) {
                        if (!mPlayer.isPlaying()) {
                            mPlayer.start();
                            playbtn.setImageResource(R.drawable.ic_stop);
                        }
                    }
                    mHandler.removeMessages(3);
                } else {
                    if (!isfinish&&!isPay) {
                        getIsPay();
                        mHandler.sendEmptyMessageDelayed(3, 3000);
                    }

                }
            }
//            if(msg.what == 100){
//                mPlayer.seekTo(0);
//            }




        }
    };





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_vod_player);


        mVideoUrl=getIntent().getStringExtra("playurl");

//        mVideoUrl="http://120.78.51.56:10000/uploadVideo/20171012/1507808254483.mp4";
        freeDuratio=getIntent().getIntExtra("freeDuratio",0);
        mLastPosition=getIntent().getIntExtra("playpoint",0);
        Log.i("VODPlayer", "传过来观看记录"+mLastPosition);
        DebugUtil.i("rrrrr","mVideoUrl="+mVideoUrl);


//        Toast.makeText(this,"播放串："+mVideoUrl,Toast.LENGTH_LONG).show();

        if(GlobalParams.user_paytype.equals("1")&&!isPay&&freeDuratio>0){
            Toast.makeText(this,"试看"+freeDuratio+"秒，请购买观看完整影片",Toast.LENGTH_SHORT).show();
            freeDuratio=freeDuratio*1000;
        }


        mBufferingPage = (RelativeLayout) findViewById(R.id.vod_buffering_hint_page);
        mBufferingHint = (TextView) findViewById(R.id.tv_buffering_progress);

        mVideoViewParentLayout = (RelativeLayout) findViewById(R.id.vod_player_view_parent);
        RelativeLayout.LayoutParams videoViewParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
        videoViewParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
        mVideoView = new VodVideoView(this);
        mVideoView.setLayoutParams(videoViewParams);
        mVideoViewParentLayout.addView(mVideoView, 0);

        mSurfaceHolder = mVideoView.getHolder();
        mSurfaceHolder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                if (mPlayer == null) {
                    mPlayer = new MediaPlayer();
                    mPlayer.setScreenOnWhilePlaying(true);
                    mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

                    mPlayer.setOnPreparedListener(VODPlayActivity.this);
                    mPlayer.setOnBufferingUpdateListener(VODPlayActivity.this);
                    mPlayer.setOnCompletionListener(VODPlayActivity.this);
                    mPlayer.setOnErrorListener(VODPlayActivity.this);
                    mPlayer.setOnInfoListener(VODPlayActivity.this);
                }
            }

            @Override
            public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

                if (mPlayer != null) {
                    mPlayer.setDisplay(holder);
                    if (!mPlayer.isPlaying()) {
                        startupPlay();
                    }
                }


            }

            @Override
            public void surfaceDestroyed(SurfaceHolder holder) {
            }
        });

        //播放控制相关
        mVgControlPanel = (ViewGroup) findViewById(R.id.view_vod_control_panel);
        mSeekBar = (SeekBar) findViewById(R.id.sk_vod_seek_bar);
        playbtn=(ImageView) findViewById(R.id.playbtn);
        mTvCurrentPosition = (TextView) findViewById(R.id.tv_vod_current_positon);
        mTvDuration = (TextView) findViewById(R.id.tv_vod_duration);


        //延迟隐藏
        mPanelDelayHideHandler = new Handler();
        mNeedDelayHideViews = new ArrayList<>();




        payinfolay=(RelativeLayout) findViewById(R.id.payinfolay);
        pay_price_text=(TextView) findViewById(R.id.pay_price_text);
        wxcode=(ImageView) findViewById(R.id.wxcode);
        alcode=(ImageView) findViewById(R.id.alcode);

        wxpic=getIntent().getStringExtra("wxpic");
        alpic=getIntent().getStringExtra("alpic");
        price=getIntent().getStringExtra("price");
        contentid=getIntent().getStringExtra("contentid");

        sendplayRecord();

    }



    private void startupPlay() {
        if(mPlayer!=null) {//10月25日添加 防止空指针

            if (mPlayer.isPlaying())
                return;

            mBufferingPage.setVisibility(View.VISIBLE);
            try {
                mPlayer.setDataSource(mVideoUrl);
                mPlayer.prepareAsync();


            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }



    private void updatePanelInfo() {
        if (mPlayer != null && mPlayer.isPlaying()) {
            int duration = mPlayer.getDuration();
            final int current = mPlayer.getCurrentPosition();

            mTvDuration.setText(TimeUtil.secToTime(duration / 1000));
            mTvCurrentPosition.setText(TimeUtil.secToTime(current / 1000));
            mSeekBar.setProgress(current * mSeekBar.getMax() / duration);
            mSeekBar.postDelayed(new Runnable() {
                @Override
                public void run() {



                    if (GlobalParams.user_paytype.equals("1")&&!isPay&&freeDuratio!=0&&current>=freeDuratio){

                        mHandler.sendEmptyMessage(1);


                    }else{
                        updatePanelInfo();
                    }


                }
            }, 1000);
        }

    }



    private void showControlPane() {
        if (!mVgControlPanel.isShown()) {
            mVgControlPanel.startAnimation(AnimationUtils.loadAnimation(this, R.anim.bottom_fade_in));
            mVgControlPanel.setVisibility(View.VISIBLE);
        }
        updatePanelInfo();
        delayHide(mVgControlPanel);
    }


    private void delayHide(View view) {

        if (mNeedDelayHideViews.indexOf(view) < 0) {
            mNeedDelayHideViews.add(view);
        }

        //延迟自动隐藏控制面板
        if (mPanelDelayHideRunnable != null) {
            mPanelDelayHideHandler.removeCallbacks(mPanelDelayHideRunnable);
            mPanelDelayHideRunnable = null;
        }

        mPanelDelayHideRunnable = new Runnable() {
            @Override
            public void run() {
                if (mPlayer != null && mPlayer.isPlaying()) {
                    for (View view : mNeedDelayHideViews) {
                        view.startAnimation(AnimationUtils.loadAnimation(VODPlayActivity.this, R.anim.bottom_fade_out));//动画取消
                        view.setVisibility(View.INVISIBLE);
                    }
                }

                mNeedDelayHideViews.clear();
            }
        };
        mPanelDelayHideHandler.postDelayed(mPanelDelayHideRunnable, 2000);
    }






    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode != KeyEvent.KEYCODE_BACK&&payinfolay.getVisibility()==View.VISIBLE) {
             return true;
        }


        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(freeDuratio==0){
                mLastPosition = mPlayer.getCurrentPosition();
                sendplayPoint(mLastPosition);
            }
        }


        if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
            if (!mVgControlPanel.isShown()) {
                mVgControlPanel.startAnimation(AnimationUtils.loadAnimation(this, R.anim.bottom_fade_in));
                mVgControlPanel.setVisibility(View.VISIBLE);
            }
//            if (!mVgControlPanel.isShown()) {
//                mVgControlPanel.startAnimation(AnimationUtils.loadAnimation(this, R.anim.bottom_fade_in));
//            }
            if (mVgControlPanel.getVisibility() == View.VISIBLE) {
                if (mPlayer != null) {
                    if (mPlayer.isPlaying()) {
                        mPlayer.pause();
                        playbtn.setImageResource(R.drawable.ic_play);
                        mLastPosition = mPlayer.getCurrentPosition();
                    } else {
                        mPlayer.start();
                        playbtn.setImageResource(R.drawable.ic_stop);
                    }

                }
            }
        }

        if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT ) {
            if (mVgControlPanel.getVisibility() == View.VISIBLE) {
                int current = mPlayer.getCurrentPosition();
                int duration = mPlayer.getDuration();
                current -= 15000;
                if (current < 0) {
                    current = 0;
                }
                if (mPlayer.isPlaying()) {
                    mPlayer.seekTo(current);
//                    isCanSeek=true;
                }

            }
        }

        if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ) {
            if (mVgControlPanel.getVisibility() == View.VISIBLE) {
//                isCanSeek=false;
                try {
                    int current = mPlayer.getCurrentPosition();
                    int duration = mPlayer.getDuration();
                    current += 15000;
                    if (current < duration) {
                        if (mPlayer.isPlaying()) {
                            mPlayer.seekTo(current);
//                            isCanSeek=true;
                        }
                    }
                } catch (Exception e) {

                }


            }
        }

        if (keyCode == KeyEvent.KEYCODE_ENTER
                || keyCode == KeyEvent.KEYCODE_DPAD_CENTER
                || keyCode == KeyEvent.KEYCODE_MENU
                || keyCode == KeyEvent.KEYCODE_DPAD_LEFT
                || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {
            showControlPane();
        }



        if (keyCode == KeyEvent.KEYCODE_DPAD_UP) {
            //TODO
        } else if (keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
            //TODO
        }


        return super.onKeyDown(keyCode, event);
    }




    @Override
    protected void onDestroy() {
        super.onDestroy();

        releaseMediaPlayer();
        isfinish=true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mPlayer != null) {
            if (mPlayer.isPlaying()) {
                mPlayer.pause();
            }
        }

    }

    private void releaseMediaPlayer() {

        try {
            if (mPlayer != null) {
                /*if(mPlayer.isPlaying()) {
                    mPlayer.stop();
                }*/
                mPlayer.stop();
                mPlayer.reset();
                mPlayer.release();
                mPlayer = null;


            }
        } catch (java.lang.IllegalStateException e) {
            e.printStackTrace();
        }


    }


    XWDialog_yes yl;

    /**
     * MediaPlayer.OnPreparedListener
     */
    @Override
    public void onPrepared(MediaPlayer mp) {



        int h= mp.getVideoHeight();
        int w= mp.getVideoWidth();
        mVideoView.setContentSize(w,h);
        mPlayer.start();


        if (mLastPosition > 0&&freeDuratio==0) {
            mPlayer.seekTo(mLastPosition);

             yl=  new XWDialog_yes(VODPlayActivity.this, "已定位到上次观看位置", true, new XWDialog_yes.OnCustomDialogListener() {
                @Override
                public void back(String name) {
                    //mPlayer.seekTo(0);
                }
            });
            yl.setTimeDisminss(5,"重新播放");
            yl .show();
        }
    }

    /**
     * MediaPlayer.OnBufferingUpdateListener
     */
    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        Log.v(TAG, "buffering process: " + percent);

        String format = "缓冲中...(%1$d％)";
        mBufferingHint.setText(String.format(format, percent));

        if (mPlayer.getCurrentPosition() > 0 && mBufferingPage.getVisibility() == View.VISIBLE) {
            mBufferingPage.setVisibility(View.INVISIBLE);
            showControlPane();
        }
    }

    /**
     * MediaPlayer.OnCompletionListener
     */
    @Override
    public void onCompletion(MediaPlayer mp) {
        //TODO
        Log.v(TAG, "onCompletion");

        mLastPosition =0;
        sendplayPoint(mLastPosition);

        if(yl!=null){
            yl.dismiss();
        }

        finish();


    }





    /**
     * MediaPlayer.OnInfoListener
     */
    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        // TODO Auto-generated method stub
        Log.i("VODPlayer", "onInfo=" + what+",extra="+extra);
        switch (what) {
            case MediaPlayer.MEDIA_INFO_BUFFERING_END:
            case MediaPlayer.MEDIA_INFO_VIDEO_RENDERING_START:
                mBufferingPage.setVisibility(View.INVISIBLE);
                showControlPane();
                break;
            default:
               // Log.i("VODPlayer", "执行了onInfo,并且抛出了(" + what + ")状态码!");
        }
        return false;
    }

    /**
     * r
     * MediaPlayer.OnErrorListener
     */
    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        // TODO Auto-generated method stub
        Log.i("VODPlayer", "onError=" + what+",extra="+extra);
        if(what == -2){
           // mPlayer.reset();
        }
        switch (what) {
            case 54000:

                break;

            default:
               // Log.i("VODPlayer", "执行了onError,并且抛出了(" + what + ")错误码!");
        }

        return false;
    }




    private void getIsPay(){

        try {

            /**
             * ---------------body------------------
             */
            JSONObject body = new JSONObject();
//            {"sn":"设备号","conentid":"购买影片Id","accountid":"用户id"}
            body.put("sn", GlobalParams.SN);
            body.put("contentid", contentid);
            body.put("accountid", GlobalParams.user_id);



            RequestParams params = new RequestParams(GlobalParams.reqHost + "attestation/ispay");
            params.setAsJsonContent(true);
            params.setBodyContent(body.toString().trim());

            /**
             * ---------------send------------------
             */
            x.http().post(params, new org.xutils.common.Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String s) {
                    try {
                        JSONObject jData=new JSONObject(s);

                        JSONObject respbody=jData.getJSONObject("respbody");
                        JSONObject data=respbody.getJSONObject("data");
                        if (data.getInt("ispay")==1){
                            isPay=true;
                        }


                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFinished() {

                }

                @Override
                public void onCancelled(CancelledException e) {

                }

                @Override
                public void onError(Throwable throwable, boolean b) {

                }
            });


        }catch (Exception e){
            e.printStackTrace();
        }

    }



    private void sendplayRecord(){

        try {



            /**
             * ---------------body------------------
             */
            JSONObject body = new JSONObject();
            body.put("sn", GlobalParams.SN);
            body.put("contentid", contentid);
            body.put("accountid", GlobalParams.user_id);

            RequestParams params = new RequestParams(GlobalParams.reqHost + "account/playRecord");
            params.setAsJsonContent(true);
            params.setBodyContent(body.toString().trim());

            /**
             * ---------------send------------------
             */
            x.http().post(params, new org.xutils.common.Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String s) {

                }

                @Override
                public void onFinished() {

                }

                @Override
                public void onCancelled(CancelledException e) {

                }

                @Override
                public void onError(Throwable throwable, boolean b) {

                }
            });

        }catch (Exception e){
            e.printStackTrace();
        }

    }






    private void sendplayPoint(int mLastPosition){

        try {



            /**
             * ---------------body------------------
             */
            JSONObject body = new JSONObject();
            body.put("sn", GlobalParams.SN);
            body.put("contentid", contentid);
            body.put("accountid", GlobalParams.user_id);
            body.put("point", mLastPosition+"");

            Log.i("VODPlayer", "观看记录"+mLastPosition);

            RequestParams params = new RequestParams(GlobalParams.reqHost + "content/point");
            params.setAsJsonContent(true);
            params.setBodyContent(body.toString().trim());

            /**
             * ---------------send------------------
             */
            x.http().post(params, new org.xutils.common.Callback.CommonCallback<String>() {
                @Override
                public void onSuccess(String s) {

                    try {
                        JSONObject jData=new JSONObject(s);



                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }

                @Override
                public void onFinished() {

                }

                @Override
                public void onCancelled(CancelledException e) {

                }

                @Override
                public void onError(Throwable throwable, boolean b) {

                }
            });

        }catch (Exception e){
            e.printStackTrace();
        }

    }


}
